﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace updater
{
    class updater
    {
        private string startdir;
        private string[] files;

        public updater()
        {
            //uac elevation
            this.startdir = Path.GetDirectoryName(Assembly.GetAssembly(typeof(updater)).Location);
            this.files = Directory.GetFiles(this.startdir, "*.repl");

            //shutdown conflicting programs
            Process[] runing = Process.GetProcesses();
            DialogResult dr;
            bool conflict = false;
            foreach (Process p in runing)
            {
                if (p.ProcessName.ToLower() == "calcsharp.exe" || p.ProcessName.ToLower() == "pkgman.exe")
                {
                    if (Path.GetDirectoryName(p.StartInfo.FileName) == this.startdir)
                    {
                        conflict = true;
                        break;
                    }
                }
            }
            if (conflict)
            {
                dr = MessageBox.Show("A conflicting program is running. Do you want to shut it down ?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
                if (dr == DialogResult.Yes)
                {
                    runing = Process.GetProcesses(); //refresh process list
                    foreach (Process p in runing)
                    {
                        if (p.ProcessName.ToLower() == "calcsharp.exe" || p.ProcessName.ToLower() == "pkgman.exe")
                        {
                            if (Path.GetDirectoryName(p.StartInfo.FileName) == this.startdir) p.Kill();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Update process can't be completed. The updater exits.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Environment.Exit(1);
                }
            }
        }

        public void Run()
        {
            foreach (string f in this.files)
            {
                //vendor check itt
                File.Move(f, f.Replace(".repl", ""));
            }
        }
    }
}
